﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HandyControl.Controls;
using HandyControl.Tools;
using HandyControl.Data;
using HandyControl.Properties.Langs;
using MyHelper;
using HandyControl.Tools.Extension;
using Button = System.Windows.Controls.Button;
using Image = System.Windows.Controls.Image;

namespace weighing
{
    /// <summary>
    /// NoUserContent.xaml 的交互逻辑
    /// </summary>
    public partial class NoUserContent
    {
        public object Messenger { get; private set; }

        public NoUserContent()
        {
            InitializeComponent();
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) return;
        }

        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            SetLoginUserInfo();

            InitMainViewMenu();

            DelegeteFactory.Instance.OnDefaultScaleHouseChanged += OnDefaultScaleHouseChanged;
            DelegeteFactory.Instance.OnWeighingWeighingModeChanged += OnWeighingWeighingModeChanged;
            DelegeteFactory.Instance.onUserCompanyChanged += OnUserCompanyChanged;
            #region Toggle menu according to software version
            Task.Delay(1300).ContinueWith(t =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    UpdateUIByMode();
                });
            });
            #endregion
        }

        private void OnDefaultScaleHouseChanged(ScaleHouseVo houseVo)
        {
            if (houseVo != null)
            {
                this.houseTb.Text = houseVo.Name;
            }
        }

        private void OnWeighingWeighingModeChanged(WeighingMode mode)
        {
            UpdateUIByMode();
        }

        private void OnUserCompanyChanged(CompanyVo companyVo)
        {
            this.companyTb.Text = App.CurrentCompanyVo?.FullName;
        }
        private void UpdateUIByMode()
        {
            if (App.Config.WeighingConfig.WeighingMode == WeighingMode.Simple)
            {
                this.inDataMenu.Visibility = Visibility.Collapsed;
                this.outDataMenu.Visibility = Visibility.Collapsed;
                this.selfDataMenu.Visibility = Visibility.Collapsed;
                this.foreignDataMenu.Visibility = Visibility.Collapsed;
                this.mixtureDataMenu.Visibility = Visibility.Visible;
                this.InWeighingMI.Visibility = Visibility.Collapsed;
                this.InDataMI.Visibility = Visibility.Collapsed;
                this.OutWeighingMI.Visibility = Visibility.Collapsed;
                this.OutDataMI.Visibility = Visibility.Collapsed;

            }
            else
            {
                if (CommonFunction.HasPermision(PermissionKeys.WeighingDataIn))
                {
                    this.inDataMenu.Visibility = Visibility.Visible;
                }
                if (CommonFunction.HasPermision(PermissionKeys.WeighingDataOut))
                {
                    this.outDataMenu.Visibility = Visibility.Visible;
                }
                if (CommonFunction.HasPermision(PermissionKeys.WeighingDataIn))
                {
                    this.selfDataMenu.Visibility = Visibility.Visible;
                }
                if (CommonFunction.HasPermision(PermissionKeys.WeighingDataOut))
                {
                    this.foreignDataMenu.Visibility = Visibility.Visible;
                }
                this.mixtureDataMenu.Visibility = Visibility.Collapsed;


                this.InWeighingMI.Visibility = Visibility.Visible;
                this.InDataMI.Visibility = Visibility.Visible;
                this.OutWeighingMI.Visibility = Visibility.Visible;
                this.OutDataMI.Visibility = Visibility.Visible;

            }
        }

        /// <summary>
        ///设置登录用户的登录信息
        /// </summary>
        private void SetLoginUserInfo()
        {
            this.userName.Text = App.CurrentUser.name;
            this.roleTb.Text = RoleDao.Instance.ConverterName(App.CurrentUser.Id);
            this.companyTb.Text = App.CurrentCompanyVo.FullName;
            if (!App.CurrentUser.headerImg.IsNullOrEmpty())
            {
                var img = new Image()
                {
                    Source = (ImageSource)new ImageSourceConverter().ConvertFromString(App.CurrentUser.headerImg),
                    Stretch = Stretch.Fill,
                };
                this.userGravatar.Content = img;
                this.userLagerGravatar.Content = img;
                img.ImageFailed += (o, a) =>
                {
                    this.userGravatar.Content = null;
                    this.userGravatar.Id = App.CurrentUser.id.ToString();
                    this.userLagerGravatar.Id = App.CurrentUser.id.ToString();
                };
            }
            else
            {
                this.userGravatar.Id = App.CurrentUser.id.ToString();
                this.userLagerGravatar.Id = App.CurrentUser.id.ToString();
            }

            if (App.CurrentScaleHouseVo != null)
            {
                this.houseTb.Text = App.CurrentScaleHouseVo.Name;
            }
        }

        #region 隐藏一些高级权限的菜单 用不到，不删除

        /// <summary>
        /// 隐藏一些高级权限的菜单
        /// </summary>
        private void HideMenu()
        {
            switch (App.CurrentUser.roleType)
            {
                case (int)UserRoleType.Developer:
                    //显示所有菜单
                    break;
                case (int)UserRoleType.WeighingManager:
                    //initCompanyMenu 初始化使用单位
                    this.initCompanyMenu.Visibility = Visibility.Collapsed;

                    break;
                case (int)UserRoleType.Weighinger:

                    //initCompanyMenu 初始化使用单位
                    this.initCompanyMenu.Visibility = Visibility.Collapsed;

                    //用户管理
                    this.userMenu.Visibility = Visibility.Collapsed;
                    //设备管理
                    this.deviceMenu.Visibility = Visibility.Collapsed;
                    //摄像头
                    this.cameraMenu.Visibility = Visibility.Collapsed;

                    break;
                default:
                    break;
            }
        }

        #endregion

        #region Lang and thremes popup
        private void ButtonConfig_OnClick(object sender, RoutedEventArgs e) => PopupConfig.IsOpen = true;


        private void ButtonLangs_OnClick(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is Button btn)
            {
                PopupConfig.IsOpen = false;
                string langName = btn.Tag.ToString();
                if (langName.Equals(GlobalData.Config.LangName))
                {
                    return;
                }
                try
                {
                    ConfigHelper.Instance.SetLang(langName);
                }
                catch (Exception)
                {
                }

                GlobalData.Config.LangName = langName;
                LangHelper.UpdateLang();
                GlobalData.Save();
            }
        }


        private void ButtonSkins_OnClick(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is Button button && button.Tag is SkinType tag)
            {
                PopupConfig.IsOpen = false;
                if (tag.Equals(GlobalData.Config?.Skin)) return;
                GlobalData.Config.Skin = tag;
                GlobalData.Save();

                SkinHelper.UpdateSkin(tag);
            }
        }
        #endregion



        private void MenuAbout_OnClick(object sender, RoutedEventArgs e)
        {
            new AboutWindow
            {
                Owner = System.Windows.Application.Current.MainWindow
            }.Show();
        }


        #region 用户信息区

        private void userPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.userPopup.IsOpen = true;
        }


        #endregion

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Logout_menu_Click(object sender, RoutedEventArgs e)
        {
            App.CurrentUser = null;
            App.IsLogOut = true;

            new LoginWindow() { IsChangeAccount = true }.Show();
            App.Current.MainWindow?.Close();

        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdatePwd_menu_Click(object sender, RoutedEventArgs e)
        {
            new PasswordWindow() { Owner = App.Current.MainWindow }.ShowDialog();
        }
        #region  管理
        /// <summary>
        /// 用户管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void userMenu_Click(object sender, RoutedEventArgs e)
        {
            if (App.CurrentUser.roleType == (int)UserRoleType.Weighinger)
            {
                Growl.InfoGlobal("你没有操作权限");
                this.userMenu.Visibility = Visibility.Collapsed;
                return;
            }
            new UserWindow() { Owner = App.Current.MainWindow, }.Show();
        }
        /// <summary>
        /// 磅称管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void scaleMenu_Click(object sender, RoutedEventArgs e)
        {
            if (App.CurrentUser.roleType == (int)UserRoleType.Weighinger)
            {
                Growl.InfoGlobal("你没有操作权限");
                this.userMenu.Visibility = Visibility.Collapsed;
                return;
            }
            new ScaleWindow() { Owner = App.Current.MainWindow, }.Show();
        }

        #endregion


        #region 系统设置

        /// <summary>
        /// 初始化使用单位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void initCompanyMenu_Click(object sender, RoutedEventArgs e)
        {
            if (App.CurrentUser?.roleType != (int)UserRoleType.Developer)
            {
                Growl.InfoGlobal("你没有操作权限");
                this.initCompanyMenu.Visibility = Visibility.Collapsed;
                return;
            }
            new CompanyInitWindow() { Owner = App.Current.MainWindow }.Show();
        }


        /// <summary>
        /// 磅单设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BillSettingMenu_Click(object sender, RoutedEventArgs e)
        {
            new BillSettingWindow() { Owner = App.Current.MainWindow }.ShowDialog();
        }

        /// <summary>
        /// 磅单编号设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BillNumberSettingMenu_Click(object sender, RoutedEventArgs e)
        {
            new BillNumberSettingWin() { Owner = App.Current.MainWindow }.ShowDialog();
        }

        /// <summary>
        /// 磅单截图设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void billImageSettingMenu_Click(object sender, RoutedEventArgs e)
        {
            new ImgSettingWindow() { Owner = App.Current.MainWindow }.ShowDialog();
        }
        #endregion

        #region 数据

        private void companyMenu_Click(object sender, RoutedEventArgs e)
        {
            new CompanyWindow() { Owner = App.Current.MainWindow }.Show();
        }



        private void materialMenu_Click(object sender, RoutedEventArgs e)
        {
            new MaterialWindow() { Owner = App.Current.MainWindow }.Show();
        }

        private void carMenu_Click(object sender, RoutedEventArgs e)
        {
            new CarWindow() { Owner = App.Current.MainWindow }.Show();
        }



        private void InDataMenu_Click(object sender, RoutedEventArgs e)
        {
            new ReportWindow()
            {
                Owner = App.Current.MainWindow,
                BillType = WeightingBillType.Buy,
            }.Show();
        }

        private void OutDataMenu_Click(object sender, RoutedEventArgs e)
        {
            new ReportWindow()
            {
                Owner = App.Current.MainWindow,
                BillType = WeightingBillType.Sale,
            }.Show();
        }

        private void SelfDataMenu_Click(object sender, RoutedEventArgs e)
        {
            new ReportWindow()
            {
                Owner = App.Current.MainWindow,
                BillType = WeightingBillType.Self,
            }.Show();
        }

        private void ForeignDataMenu_Click(object sender, RoutedEventArgs e)
        {
            new ReportWindow()
            {
                Owner = App.Current.MainWindow,
                BillType = WeightingBillType.Foreign,
            }.Show();
        }

        private void MixtureDataMenu_Click(object sender, RoutedEventArgs e)
        {
            new ReportWindow()
            {
                Owner = App.Current.MainWindow,
                BillType = WeightingBillType.Mixture,
            }.Show();
        }
        /// <summary>
        /// 磅单补录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BuluDataMenu_Click(object sender, RoutedEventArgs e)
        {
            new BuLuWindow() { Owner = App.Current.MainWindow }.Show();
        }
        #endregion


        #region debug
        private void testReadDateMenu_Click(object sender, RoutedEventArgs e)
        {
            new TestScaleWindow() { Owner = App.Current.MainWindow }.Show();
        }

        #endregion



        //角色管理
        private void RoleMenu_Click(object sender, RoutedEventArgs e)
        {
            new RoleWindow() { Owner = App.Current.MainWindow }.Show();
        }
        //权限管理
        private void PermMenu_Click(object sender, RoutedEventArgs e)
        {
            new PermissionWindow() { Owner = App.Current.MainWindow }.Show();
        }

        #region 窗口菜单
        private bool IsInitMenu = true;
        /// <summary>
        /// 初始化主窗口的窗口界面菜单项
        /// </summary>
        public void InitMainViewMenu()
        {
            IsInitMenu = true;

            this.InDataMI.IsChecked = App.Config.UserConfig.ShowInData;
            this.OutDataMI.IsChecked = App.Config.UserConfig.ShowOutData;
            this.InWeighingMI.IsChecked = App.Config.UserConfig.ShowInWeighing;
            this.OutWeighingMI.IsChecked = App.Config.UserConfig.ShowOutWeighing;
            this.InWeighingMI.IsEnabled = true;
            this.OutWeighingMI.IsEnabled = true;
            InDataMI.IsEnabled = App.Config.UserConfig.ShowVideoArea;
            OutDataMI.IsEnabled = App.Config.UserConfig.ShowVideoArea;
            this.VideoAreaMI.IsChecked = App.Config.UserConfig.ShowVideoArea;
            IsInitMenu = false;
        }


        //窗口
        private void WindowsMI_Changed(object sender, RoutedEventArgs e)
        {
            if (IsInitMenu) return;
            if (sender is MenuItem mi)
            {
                string miName = mi.Name;
                MainWindow? mw = App.Current.MainWindow as MainWindow;
                if (mw == null) return;
                bool update;
                switch (miName)
                {
                    case nameof(MenuItemName.VideoAreaMI):
                        VideoAreaMI.IsEnabled = false;
                        App.Config.UserConfig.ShowVideoArea = mi.IsChecked;
                        mw.ShowOrHideVideo(true);
                        InDataMI.IsEnabled = mi.IsChecked;
                        OutDataMI.IsEnabled = mi.IsChecked;
                        update = true;
                        VideoAreaMI.IsEnabled = true;
                        break;

                    default:
                        update = false;
                        break;
                }

                if (update)
                {
                    CommonFunction.UpdateAppConfig(nameof(UserConfig));
                }

                if (mw.WeighingUIBorder.Child is NomalWeighingUc nouc)
                {
                    nouc.RelayoutByMenumItem(miName);
                }
            }
        }

        private bool LeastSelectOne(MenuItem mi)
        {
            if (this.OutWeighingMI.IsChecked == false && this.InWeighingMI.IsChecked == false)
            {
                mi.IsChecked = !mi.IsChecked;
                string msg = "采购过磅和销售到少显示一个。";
                CommonFunction.AlertInfo(msg);
                return false;
            }
            return true;
        }

        #endregion





        #region 重量单位设置
        private void UnitSettMI_Click(object sender, RoutedEventArgs e)
        {
            new UnitSettingW() { Owner = App.Current.MainWindow }.Show();
        }

        #endregion

        #region 关闭系统
        private void CloseSystemMI_Click(object sender, RoutedEventArgs e)
        {
            string msg = "是否要退出称重系统？";
            var res = CommonFunction.Ask(msg);
            if (res == MessageBoxResult.Yes)
            {
                App.Current.Shutdown();
            }
        }
        #endregion


        //自定义打印模板设置
        private void CustomerPrintBillSettingMenu_Click(object sender, RoutedEventArgs e)
        {
            new CustomizePrintBillWin()
            {
                Owner = App.Current.MainWindow,
            }.Show();
        }

        //年报表
        private void YearReportMenu_Click(object sender, RoutedEventArgs e)
        {
            new ReportSummaryWindow(ReportSummaryWindow.YearReport)
            {
                Owner = App.Current.MainWindow,
            }.Show();
        }

        //月报表
        private void MonthReportMenu_Click(object sender, RoutedEventArgs e)
        {
            new ReportSummaryWindow(ReportSummaryWindow.MonthReport)
            {
                Owner = App.Current.MainWindow,
            }.Show();
        }

        //日报表
        private void DayReportMenu_Click(object sender, RoutedEventArgs e)
        {
            new ReportSummaryWindow(ReportSummaryWindow.DayReport)
            {
                Owner = App.Current.MainWindow,
            }.Show();
        }

        /// <summary>
        /// 磅房信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScaleHouseMenu_Click(object sender, RoutedEventArgs e)
        {
            new ScaleHouseWindow()
            {
                Owner = App.Current.MainWindow
            }.Show();
        }

        /// <summary>
        /// 默认磅房设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HouseSettingMenu_Click(object sender, RoutedEventArgs e)
        {
            new HouseConfigWindow()
            {
                Owner = App.Current.MainWindow
            }.Show();
        }

        private void ActiveCodeMenu_Click(object sender, RoutedEventArgs e)
        {

        }

        private void CameraMenu_Click(object sender, RoutedEventArgs e)
        {
            new CameraWindow()
            {
                Owner = App.Current.MainWindow
            }.Show();
        }

        private void SystemViewModeMenu_Click(object sender, RoutedEventArgs e)
        {
            new WeighingConfigWindow()
            {
                Owner = App.Current.MainWindow
            }.Show();            
        }

        // EXCL　BIll
        private void CustomerExclBillSettingMenu_Click(object sender, RoutedEventArgs e)
        {
            new CustomizeEXCLPrintBillWin()
            {
                Owner = App.Current.MainWindow
            }.Show();
        }
    }
}
